package com.zaofan.mobile.control;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zaofan.bean.Address;
import com.zaofan.bean.CouponUser;
import com.zaofan.bean.OpenBuilder;
import com.zaofan.bean.Recharge;
import com.zaofan.mobile.bean.Account;
import com.zaofan.mobile.bean.PayRequest;
import com.zaofan.service.AccountService;
import com.zaofan.service.AddressService;
import com.zaofan.service.OpenBuilderService;
import com.zaofan.service.RechargeService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.StringUtil;
import com.zaofan.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/31.
 */
@Controller
@RequestMapping("ucenter")
public class UcenterController {

    @RequestMapping("/addAddress.do")
    public String addAddress(HttpServletRequest request,String id,String target,Address parm, ModelMap modelMap){


        AddressService addressService = new AddressService();
        OpenBuilderService ob = new OpenBuilderService();
        Address address = null;
        //返回键的url地址
        String starget = null;

        if (!StringUtils.isEmpty(target))
         starget = target;

        if (!StringUtils.isEmpty(id)) {
            address = addressService.findById(Integer.valueOf(id));
            request.getSession().setAttribute("sAddress",address);
            request.getSession().setAttribute("starget",starget);
        }
        
        if (address == null){
            address = new Address();
            modelMap.put("action", "add");
        }else {
            modelMap.put("action", "update");
            request.getSession().removeAttribute("sAddress");
        }

        if (parm != null && parm.getBuilderId()>0){
            OpenBuilder temp = ob.findById(parm.getBuilderId());
            address = (Address) request.getSession().getAttribute("sAddress");
            starget = (String) request.getSession().getAttribute("starget");

            if (address == null){
                address = new Address();
                modelMap.put("action", "add");
            }else {
                modelMap.put("action", "update");
                request.getSession().removeAttribute("sAddress");
            }
            String name = (String) request.getSession().getAttribute("chooseAreaName");
            String phone=(String)request.getSession().getAttribute("chooseAreaPhone");
            if (name==null){
                name="";
            }
            if(phone==null){
                phone="";
            }
            address.setConsignee(name);
            address.setPhone(phone);
            address.setBuilderId(temp.getId());
            address.setBuilderName(temp.getBuilderName());
//            Map<String,Object> map = new HashMap<>();
//            map.put("builderId",temp.getId());
//            map.put("builderName",temp.getBuilderName());
        }

        modelMap.put("dizhi",address);
        modelMap.put("target","/ucenter/myAddress.do");
        modelMap.put("title","收货地址");
        modelMap.put("backBt","/ucenter/myAddress.do");
        return "/ucenter/addAddress";
    }

    @RequestMapping("/index.do")
    public String index(HttpServletRequest request, ModelMap modelMap){
        modelMap.put("title","个人中心");
        return "/ucenter/index";
    }

    @RequestMapping("/chooseAddress.do")
    public void chooseAddress(HttpServletRequest request, HttpServletResponse response,String id){
        AddressService addressService = new AddressService();
        Address address = addressService.findById(Integer.valueOf(id));
        request.getSession().setAttribute("address",address);
        JsonUtils.writeSuccessJson("操作成功",address,response);
    }

    @RequestMapping("/chooseCoupon.do")
    public void chooseCoupon(HttpServletRequest request,HttpServletResponse response){
        request.getSession().setAttribute("CouponUserId",request.getParameter("CouponUserId"));
        request.getSession().setAttribute("CouponId",request.getParameter("CouponId"));
        request.getSession().setAttribute("CouponName", request.getParameter("CouponName"));
        JsonUtils.writeSuccessJson("操作成功",new Object(),response);
    }



    @RequestMapping("/myAddress.do")
    public String myAddress(HttpServletRequest request,String choose, ModelMap modelMap){
        AddressService addressService = new AddressService();
        try {
            Account account = (Account) request.getSession().getAttribute("userinfo");
            List<Address> addresses = addressService.findByAccountId(account.getId());
            modelMap.put("addresses",addresses);
            modelMap.put("title","收货地址");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(choose)) {
            return "/ucenter/myAddress";
        }else{
            modelMap.put("backBt","/home/shopCar.do");
            return "/ucenter/chooseAddress";
        }
    }

    @RequestMapping("/myCoupon.do")
    public String myCoupon(HttpServletRequest request, ModelMap modelMap){
        Account account = (Account) request.getSession().getAttribute("userinfo");
        modelMap.put("totalPrice",request.getParameter("totalPrice"));
        modelMap.put("userinfo",account);
        return "/ucenter/coupon";
    }




    @RequestMapping("/recharge.do")
    public String recharge(HttpServletRequest request,PayRequest payRequest,ModelMap modelMap) throws IOException, ServletException {
        Map<String,String> wxpay = (Map<String, String>) request.getSession().getAttribute("wxpay");
        if (wxpay == null){
            if (payRequest == null || StringUtils.isEmpty(payRequest.getState())){
                String http = "https://open.weixin.qq.com/connect/oauth2/authorize?";
                String appid = "&appid=wxf946190506655c2d";
                String redirect_uri = "&redirect_uri=http://m.52letsgo.cn/ucenter/recharge.do";
                String response_type = "&response_type=code";
                String scope = "&scope=snsapi_base";
                String state = "&state=16516516156#wechat_redirect";
                return "redirect:"+http+appid+redirect_uri+response_type+scope+state;
            }else {
                String wxUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf946190506655c2d" +
                        "&secret=25f4e517eeea25ea18e75cab31cc3b8b&code="+payRequest.getCode()+"&grant_type=authorization_code";
                wxpay = new GsonBuilder().create().fromJson(WebUtils.doHttpRequest(wxUrl),new TypeToken<Map<String,String>>(){}.getType());
                System.out.println("wxopenid="+wxpay.get("openid"));
                request.getSession().setAttribute("wxpay",wxpay);
            }
        }
        String rechargeCityId = request.getSession().getAttribute("rechargeCityId").toString();
        String rechargeCityName = request.getSession().getAttribute("rechargeCityName").toString();
        if (StringUtils.isEmpty(rechargeCityId) || StringUtils.isEmpty(rechargeCityName)) {
        	modelMap.put("rechargeCityId","1");
        	modelMap.put("rechargeCityName","福州市");
        } else {
        	modelMap.put("rechargeCityId",rechargeCityId);
        	modelMap.put("rechargeCityName",rechargeCityName);
        }
        modelMap.put("title","充值");
        return "/ucenter/recharge";
    }

    @RequestMapping("/rechargereturn.do")
    public String rechargereturn(HttpServletRequest request) throws IOException, ServletException {
        AccountService accountService = new AccountService();
        Account userinfo = (Account)request.getSession().getAttribute("userinfo");
        Account target = accountService.findAccountInfo(userinfo.getId());
        request.getSession().setAttribute("userinfo",target);
        return "redirect:/ucenter/index.do";
    }

    @RequestMapping("/makeRecharge.do")
    public void dorecharge(HttpServletRequest request,HttpServletResponse response,String money, Integer cityId){
        Map<String,String> wxpay = (Map<String, String>) request.getSession().getAttribute("wxpay");
        Account account = (Account)request.getSession().getAttribute("userinfo");
        try {
        String paybenUrl = "http://m.52letsgo.cn/pay/payBean?" +
                "money=" + money +
                "&userId=" + account.getId() +
                "&wechatOpenid=" + wxpay.get("openid") +
                "&orderType=0" +
                "&platform=TOUCH"
                + "&cityId=" + cityId
                ;
        String paybeanres = WebUtils.doHttpRequest(paybenUrl);
        Map<String,Object> paybean = new GsonBuilder().create().fromJson(paybeanres,new TypeToken<Map<String,Object>>(){}.getType());
        JsonUtils.writeSuccessJson("成功",paybean,response);
//        modelMap.put("paybean",paybean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/rechargeRecord.do")
    public String rechargeRecord(HttpServletRequest request, ModelMap modelMap){
        RechargeService rechargeService = new RechargeService();
//        根本就没传accountId， jsp里根本没用到recharges， 
//        try {
//            Integer accountId = Integer.valueOf(request.getParameter("accountId"));
//            List<Recharge> recharge = rechargeService.findByAccountId(accountId);
//            modelMap.put("recharges",recharge);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        modelMap.put("title","充值记录");
        return "/ucenter/rechargeRecord";
    }
    @RequestMapping("/cardRecharge.do")
    public String cardRecharge(HttpServletRequest request, ModelMap modelMap){
        modelMap.put("title","充值");
        return "/ucenter/cardRecharge";
    }

    @RequestMapping("/feedback.do")
    public String feedback(HttpServletRequest request, ModelMap modelMap){
        modelMap.put("title","反馈意见");
        return "/ucenter/feedback";
    }

    @RequestMapping("/userinfo.do")
    public String userinfo(HttpServletRequest request, ModelMap modelMap){
        modelMap.put("title","个人资料");
        return "/ucenter/userinfo";
    }

}
